import dash
from dash import html, Input, Output, State
import feffery_antd_components as fac
from tqdm import tqdm
from peewee import SqliteDatabase, CharField, IntegerField, FloatField, Model

db = SqliteDatabase('demo_table.db')


class DemoTable(Model):
    field1 = CharField()
    field2 = IntegerField()
    field3 = FloatField()

    class Meta:
        table_name = 'demo_table'
        database = db


db.create_tables([DemoTable])

if DemoTable.select().count() == 0:
    with db.atomic():
        for i in tqdm(range(10)):
            _ = (
                DemoTable
                    .insert_many([
                    {
                        'field1': i,
                        'field2': f'字符{i}',
                        'field3': float(f'0.{i}')
                    }
                    for i in range(50000 * i, 50000 * (i + 1))
                ])
                    .execute()
            )

app = dash.Dash(__name__)

app.layout = html.Div(
    [
        fac.AntdSpin(
            fac.AntdTable(
                id='demo-table',
                mode='server-side',
                columns=[
                    {
                        'title': field,
                        'dataIndex': field,
                        'width': 100
                    }
                    for field in ['field1', 'field2', 'field3']
                ],
                data=list(DemoTable.select().limit(10).dicts()),
                bordered=True,
                pagination={
                    'pageSize': 10,
                    'total': DemoTable.select().count(),
                    'pageSizeOptions': [5, 10],
                    'showQuickJumper': True
                }
            )
        )
    ],
    style={
        'padding': '100px'
    }
)


@app.callback(
    Output('demo-table', 'data'),
    Input('demo-table', 'pagination'),
    prevent_initial_call=True
)
def update_table_data(pagination):
    data = (
        DemoTable
            .select()
            .limit(pagination['pageSize'])
            .offset(pagination['pageSize'] * pagination['current'] - 1)
    )

    return list(data.dicts())


if __name__ == '__main__':
    app.run_server(debug=True)
